package me.hl.lambda;

import me.hl.exception.MyException;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Planck on 2016/1/11.
 */
public class LamdaCase {


    @Test
    public void test1() throws Exception {

        List<Book> books = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            Book book = new Book(new Random().nextInt(100), "book" + i);
            books.add(book);
        }
        books = books.stream().filter(b -> b.getPrice() > 50).sorted((a, b) -> a.getPrice() - b.getPrice()).collect(Collectors.toList());
        books.forEach(System.out::print);
    }

    @Test
    public void streamtest() {
        List<Integer> nums = new ArrayList();
        nums.add(1);
        nums.add(2);
        nums.add(2);
        nums.add(null);
        nums.add(3);
        nums.add(null);
        nums.add(4);
        nums.add(null);
        nums.add(5);
        nums.add(null);
        nums.add(6);
        //过滤掉null的元素 distinct掉重复的元素 然后把这个流转化成int的流 顺便*2
        //对于每个元素都再输出一遍 跳过前2个 从第三个到第七个求和(没有第七个，于是不算)
        System.out.println("sum is:" + nums.stream().filter(num -> num != null).
                distinct().mapToInt(num -> num * 2).
                peek(System.out::println).skip(2).limit(4).sum());

        List<Integer> num = nums.stream().filter(a -> a != null).sorted((a, b) -> b - a).collect(Collectors.toList());
        num.forEach(a -> System.out.println(a));

    }


    @Test
    public void streamTest() throws Exception {
        List<Integer> num = new ArrayList();
        for (int i = 0; i <= 10; i++) {
            Random random = new Random();
            Integer a = random.nextInt(100);
            num.add(a);
        }
        num.forEach(a -> System.out.print(" " + a));
        System.out.println("\n选出大于50的排序后得到的结果：");
        num = num.stream().filter(a -> a > 50).sorted((a, b) -> a - b).collect(Collectors.toList());
        num.forEach(a -> System.out.print(" " + a));
        OptionalInt max = num.stream().mapToInt(x -> x).max();
        System.out.println();
        System.out.println(max.orElseGet(() -> 0));//orElseGet方法可以接受Supplier接口的实现用来生成默认值
        System.out.println(max.orElse(0)); //如果有值则将其返回，否则返回指定的其它值

        Optional<String> os = Optional.ofNullable(null);
        try {
            System.out.println(os.orElseThrow(() -> new MyException("aaaaaa")));//如果有值则将其返回，否则抛出supplier接口创建的异常。
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}



